<template>
    <a-modal v-model:open="showModal" :title="formTitle" @ok="confirm">
        <div class="px-[10px] mt-[30px]">
            <a-form :model="formData" ref="formRef" :label-col="{ style: { width: '60px' } }">
                <a-form-item label="角色" name="role_name" :rules="[{ required: true, message: '请输入角色' }]">
                    <a-input v-model:value="formData.role_name" placeholder="请输入角色" show-count :maxlength="10" />
                </a-form-item>
                <a-form-item label="状态" name="status">
                    <a-radio-group v-model:value="formData.status" name="status">
                        <a-radio :value="1">正常</a-radio>
                        <a-radio :value="0">停用</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="权限" name="rules" :rules="[{ required: true, message: '请设置权限' }]">
                    <div class="border-1 p-[10px]">
                        <div class="flex items-center justify-between mb-[10px]">
                            <div class="flex items-center">
                                <a-form-item-rest><a-checkbox
                                        v-model:checked="selectAll">全选</a-checkbox></a-form-item-rest>
                                <a-button type="text" @click="openMenuAction">折叠展开</a-button>
                            </div>
                            <div class="flex items-center">
                                <span class="mr-[4px]">父子级不关联</span>
                                <a-form-item-rest><a-switch v-model:checked="checkStrictly" checked-children="开"
                                        un-checked-children="关" /></a-form-item-rest>
                            </div>
                        </div>
                        <a-tree :defaultExpandAll="isOpen" :height="300" :checkStrictly="checkStrictly" v-model:selectedKeys="selectedKeys"
                            v-model:checkedKeys="formData.rules" v-model:expandedKeys="expandedKeys" checkable
                            :tree-data="treeData" :field-names="fieldNames">
                        </a-tree>
                    </div>
                </a-form-item>
            </a-form>
        </div>
    </a-modal>
</template>
<script lang="ts" setup>
import { reactive, ref, Ref, onMounted, watch } from 'vue';
import { message } from 'ant-design-vue';
import type { TreeProps } from 'ant-design-vue';
import { addAdminRole, editAdminRole } from '@/utils/api/sys';
import { getMenuList } from '@/utils/api/menu';

const showModal = ref<boolean>(false);

/**
 * 表单原始数据
 */
const initialFormData = {
    role_id: 0,
    role_name: '',
    rules: [],
    status: 1,
}

const fieldNames: TreeProps['fieldNames'] = {
    children: 'children',
    title: 'menu_name',
    key: 'menu_key',
};

const treeData: Ref<TreeProps['treeData']> = ref([]);

const selectedKeys = ref<string[]>([]);
const expandedKeys = ref<string[]>([]);
const selectAll = ref(false);
const checkStrictly = ref(false);
const isOpen = ref(false);

// 全部展开
const allMenuKey = ref<string[]>([]);
const setAllMenuKey = (data: any) => {
    Object.keys(data).forEach((key:string|any) => {
        allMenuKey.value.push(data[key].menu_key)
        if (data[key].children && data[key].children.length > 0) setAllMenuKey(data[key].children)
    })
}

// 折叠展开
const openMenuAction = () => {
    expandedKeys.value = isOpen.value ? [] :allMenuKey.value;
    isOpen.value = !isOpen.value;
}

watch(selectAll, () => {
    formData.rules = selectAll.value ? allMenuKey.value : [];
})

onMounted(() => {
    getMenuData();
});

// 初始化数据
const getMenuData = () => {
    getMenuList({}).then((res: any) => {
        treeData.value = res.data;
        // 获取所有key方便展开
        setAllMenuKey(treeData.value);
    })
};


const formData: Record<string, any> = reactive({ ...initialFormData })

const formRef = ref();

const formTitle = ref('添加角色');

const setFormData = async (row: any = null) => {
    if (row == null) {
        formTitle.value = '添加角色';
        Object.assign(formData, initialFormData);
    } else {
        formTitle.value = '编辑角色';
        Object.assign(formData, row);
    }
}

const confirm = (e: MouseEvent) => {
    console.log(formData)
    // return false;
    formRef.value
        .validate()
        .then(() => {
            if (formData.role_id > 0) {
                editAdminRole(formData).then((res: any) => {
                    if (res.code == 200) {
                        message.success(res.message)
                        showModal.value = false;
                        setTimeout(function () {
                            emit('complete');
                        }, 1000);
                    } else {
                        message.error(res.message)
                    }
                })
            } else {
                addAdminRole(formData).then((res: any) => {
                    if (res.code == 200) {
                        message.success(res.message)
                        showModal.value = false;
                        setTimeout(function () {
                            emit('complete');
                        }, 1000);
                    } else {
                        message.error(res.message)
                    }
                })
            }
        });
};

const emit = defineEmits(['complete'])

defineExpose({
    showModal,
    setFormData
})
</script>